# User authentication routes
from flask import Blueprint, request, jsonify, session
from app.models.user import (
    get_user_by_username, get_user_by_id, create_user, 
    update_user_balance, check_password
)
from app.utils.database import get_db_cursor

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/register', methods=['POST'])
def register():
    """User registration"""
    data = request.get_json()
    
    if not data or not data.get('username') or not data.get('password'):
        return jsonify({'error': 'Username and password cannot be empty'}), 400
    
    # Check if username already exists
    if get_user_by_username(data['username']):
        return jsonify({'error': 'Username already exists'}), 400
    
    # Check if email already exists
    if data.get('email'):
        conn, cursor = get_db_cursor()
        try:
            cursor.execute("SELECT * FROM users WHERE email = %s", (data['email'],))
            if cursor.fetchone():
                return jsonify({'error': 'Email already exists'}), 400
        finally:
            cursor.close()
            conn.close()
    
    try:
        user_id = create_user(
            username=data['username'],
            email=data.get('email'),
            age=data.get('age'),
            gender=data.get('gender'),
            balance=data.get('balance', 100.00),
            password=data['password']
        )
        
        user = get_user_by_id(user_id)
        return jsonify({
            'message': 'Registration successful',
            'user': {
                'user_id': user['user_id'],
                'username': user['username'],
                'email': user['email'],
                'age': user['age'],
                'gender': user['gender'],
                'balance': float(user['balance'])
            }
        }), 201
        
    except Exception as e:
        return jsonify({'error': f'Registration failed: {str(e)}'}), 500

@auth_bp.route('/login', methods=['POST'])
def login():
    """User login"""
    data = request.get_json()
    
    if not data or not data.get('username') or not data.get('password'):
        return jsonify({'error': 'Username and password cannot be empty'}), 400
    
    user = get_user_by_username(data['username'])
    
    if user and check_password(data['password'], user['password_hash']):
        session['user_id'] = user['user_id']
        session['username'] = user['username']
        
        return jsonify({
            'message': 'Login successful',
            'user': {
                'user_id': user['user_id'],
                'username': user['username'],
                'email': user['email'],
                'age': user['age'],
                'gender': user['gender'],
                'balance': float(user['balance'])
            }
        }), 200
    else:
        return jsonify({'error': 'Username or password incorrect'}), 401

@auth_bp.route('/logout', methods=['POST'])
def logout():
    """User logout"""
    session.clear()
    return jsonify({'message': 'Logout successful'}), 200

@auth_bp.route('/profile', methods=['GET'])
def get_profile():
    """Get user information"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': 'Not logged in'}), 401
    
    user = get_user_by_id(user_id)
    if not user:
        return jsonify({'error': 'User does not exist'}), 404
    
    return jsonify({
        'user': {
            'user_id': user['user_id'],
            'username': user['username'],
            'email': user['email'],
            'age': user['age'],
            'gender': user['gender'],
            'balance': float(user['balance'])
        }
    }), 200

@auth_bp.route('/balance', methods=['POST'])
def update_balance():
    """Update user balance"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': 'Not logged in'}), 401
    
    user = get_user_by_id(user_id)
    if not user:
        return jsonify({'error': 'User does not exist'}), 404
    
    data = request.get_json()
    amount = data.get('amount', 0)
    
    if amount < 0:
        return jsonify({'error': 'Recharge amount must be greater than 0'}), 400
    
    try:
        balance = update_user_balance(user_id, amount)
        return jsonify({
            'message': 'Recharge successful',
            'balance': balance
        }), 200
        
    except Exception as e:
        return jsonify({'error': f'Recharge failed: {str(e)}'}), 500
